<?php

class ContestController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('submitEntry'),
				'users'=>array('@'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Default action.
	 * @throws CHttpException when called
	 */
	public function actionIndex()
	{
		throw new CHttpException(404,Yii::t('frontend','The page your requested could not be found.'));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$entries = new CActiveDataProvider('Entry', array(
			'criteria'=>array(
				'condition'=>'contestId=:contestId AND status=:status AND deleted=0', // we need the deleted here because beforeFind does not work here',
				'params'=>array(
					':contestId'=>$id,
					':status'=>Entry::STATUS_APPROVED,
				),
			),
			'sort'=>array(
				'attributes'=>array(
					'votes'=>array(
						'label'=>Yii::t('frontend','Most Popular'),
						'default'=>'desc',
					),
					'created'=>array(
						'label'=>Yii::t('frontend','Newest'),
						'default'=>'desc',
					),
				),
				'defaultOrder'=>array(
					'votes'=>true,
				),
			),
			'pagination'=>array(
				'pageSize'=>12,
			),
		));

		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'entries'=>$entries,
		));
	}

	/**
	 * Displays the form for submitting an entry to the contest.
	 * @param $id the ID of the model to submit an entry for
	 */
	public function actionSubmitEntry($id)
	{
		$model = $this->loadModel($id);

		if (!$model->isSubmissionOpen() || $model->hasSubmittedEntry(Yii::app()->user->id))
		{
			Yii::app()->user->setFlash(WebUser::FLASH_ERROR,Yii::t('flash','Submission is not allowed for this contest.'));
			$this->redirect(array('view','id'=>$model->id));
		}

		$formModel = new EntrySubmitForm();

		if (isset($_POST['ajax']) && $_POST['ajax']==='entry-submit-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if (isset($_POST['EntrySubmitForm']))
		{
			$formModel->attributes = $_POST['EntrySubmitForm'];
			$formModel->upload = CUploadedFile::getInstance($formModel,'upload');
			if ($formModel->validate())
			{
				$entry = new Entry();
				$entry->name = $formModel->name;
				$entry->contestId = $formModel->contestId;
				$entry->status = Entry::STATUS_UNAPPROVED; // entries are not approved by default

				if (($file = $formModel->upload) !== null)
					$entry->saveImage($file);

				$entry->save(false);

				$user = Yii::app()->user->loadModel();
				$user->email = $formModel->email;
				$user->save(false);

				/** @var PHPMailer $mailer */
				$mailer = Yii::app()->mailer;
				$mailer->CharSet = Yii::app()->charset;
				$mailer->From = Yii::app()->params['systemEmail'];
				$mailer->FromName = Yii::app()->name.' '.Yii::t('email','System');
				$mailer->AddAddress(Yii::app()->params['contactEmail']);
				$mailer->Subject = Yii::t('email','New entry');
				$mailer->getView('_submitEntry',array('model'=>$model,'entry'=>$entry,'user'=>$user));
				$mailer->isHTML(true);
				$mailer->Send();
				
				Yii::app()->user->setFlash(WebUser::FLASH_INFO,Yii::t('flash','Thank you for submitting your entry!'));
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('submitEntry',array(
			'model'=>$model,
			'formModel'=>$formModel,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Contest the model
	 */
	public function loadModel($id)
	{
		$model=Contest::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
